//
//  OYHomeStatusViewModel.swift
//  weiboCopycat
//
//  Created by Orange Yu on 2016/12/4.
//  Copyright © 2016年 Orange Yu. All rights reserved.
//

import UIKit
import SDWebImage

// 用于处理首页网络请求
class OYHomeStatusViewModel: NSObject {

    lazy var homeStatusList:[OYStatusViewModel] = [OYStatusViewModel]()
    
    func loadData(scrollLoding:Bool,callBack:@escaping (Bool,String)->()) {
        
        var sinceID:Int64 = 0
        var maxID:Int64 = 0
        
        if scrollLoding {
            // 下滚加载，我们设置maxId为当前数组中最后一条微博的id
            maxID = homeStatusList.last?.statusModel?.id ?? 0
            if maxID > 0 {
                
                maxID -= 1
            }
            
        }else {
            // 下拉刷新，我们设置sinceId为当前数组中第一条微博的id
            sinceID = homeStatusList.first?.statusModel?.id ?? 0
        }
        
        OYNetWorkTools.sharedTools.loadHomeStatus (maxid: maxID,sinceid: sinceID){ (respose, error) in
            if error != nil {
                print("获取首页数据失败")
                callBack(false,"")
                return
            }else {
                let jsonDict = respose as! [String:Any]
                let statusJsonArr = jsonDict["statuses"] as! [[String:Any]]
                let modelArr: [OYStatusModel] = NSArray.yy_modelArray(with: OYStatusModel.self, json: statusJsonArr) as! [OYStatusModel]
                var tempArr: [OYStatusViewModel] = [OYStatusViewModel]()
                
                let group = DispatchGroup()
                // 遍历模型数组，将模型添加至oyStatusViewModel对象的属性中，将viewModel转为字典
                for statusModel in modelArr {
                    if statusModel.pic_urls?.count == 1 {
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string:(statusModel.pic_urls?.first?.thumbnail_pic)!), options: [], progress: nil, completed: { (image, error, _, _,_) in
                            print("原创单张图片下载完成")
                            group.leave()
                        })
                    }
                    
                    if statusModel.retweeted_status?.pic_urls?.count == 1 {
                        group.enter()
                        SDWebImageManager.shared().downloadImage(with: URL(string:(statusModel.retweeted_status?.pic_urls?.first?.thumbnail_pic)!), options: [], progress: nil, completed: { (image, error, _, _,_) in
                            print("转发单张图片下载完成")
                            group.leave()
                        })
                    }
                    
                    let oyStatusVM: OYStatusViewModel = OYStatusViewModel()
                    oyStatusVM.statusModel = statusModel
                    tempArr.append(oyStatusVM)
                }
                
                if scrollLoding {
                    self.homeStatusList.append(contentsOf: tempArr)
                }else {
                    self.homeStatusList.insert(contentsOf: tempArr, at: 0)
                }
                
                var message:String?
                if tempArr.count == 0 {
                    message = "没有新微博了"
                } else {
                    message = "更新了\(tempArr.count)条微博"
                }
            
                group.notify(queue: DispatchQueue.main, execute: {
                    print("所有单张图片都下载完毕")
                    callBack(true,message!)
                })
            }
        }
    }
}
